package com.hmz.backend.service.Impl.account;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hmz.backend.entity.User;
import com.hmz.backend.mapper.UserMapper;
import com.hmz.backend.service.account.LoginService;
import com.hmz.backend.utils.PasswordEncoder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service("loginUserService")
public class LoginUserServiceImpl implements LoginService {
    @Autowired
    UserMapper userMapper;
    @Override
    public JSONObject login(JSONObject data) {
        String userName = data.get("userName").toString();
        String password = data.get("password").toString();
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_name",userName).eq("password", PasswordEncoder.encode(password));
        User user = userMapper.selectOne(queryWrapper);
        if(user == null) return new JSONObject().set("message","登录失败！");
        else return new JSONObject().set("message","登录成功！").set("token",PasswordEncoder.getToken(user.getUserId(), "user")).set("data", JSONUtil.toJsonStr(user));


    }

    @Override
    public JSONObject getUserInfo(String token) {
        String uncode = PasswordEncoder.uncode(token.substring(4)); //获取user*
        int userId = Integer.parseInt(uncode.replace("user",""));//去除user前缀
        //System.out.println(userId);
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",userId);
        User user = userMapper.selectOne(queryWrapper);
        return new JSONObject().set("message","查询成功").set("user",JSONUtil.toJsonStr(user));
    }

}
